import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/http/Res.dart';
import 'package:ladder_cash/app/com/manage/data_upload_manage/data_upload_info.dart';

class DataUploadManage {
  static DataUploadManage? _instance;

  DataUploadManage._();

  static DataUploadManage get instance {
    if (_instance == null) {
      _instance = DataUploadManage._();
    }
    return _instance!;
  }

  List<DataUploadInfo> dataUploadInfoList = [];

  add(String url, dynamic map,
      {method = 'POST', void Function(bool result)? onResult}) {
    DataUploadInfo info = DataUploadInfo();
    info.url = url;
    info.id = DateTime.now().millisecondsSinceEpoch;
    info.data = map;
    dataUploadInfoList.add(info);
    execute();
  }

  execute() async {
    for (int i = dataUploadInfoList.length - 1; i >= 0; i--) {
      var data = dataUploadInfoList[i];
      if (data.status != 1 && data.reconnectCount < 3) {
        Res r = await HttpRequest()
            .post(data.url, data.data, parse: false, autoToast: false);
        if (r.success) {
          data.status = 2;
          dataUploadInfoList.remove(data);
        } else {
          data.reconnectCount++;
          if (data.reconnectCount >= 3) {
            data.status = 2;
            dataUploadInfoList.remove(data);
          } else {
            execute();
          }
        }
      }
    }
  }
}
